package com.xzx.java.kit.basic.reflection;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * 利用反射扩容数组
 *
 * @author xinzhixuan
 * @version V1.0
 * @date 2017/12/29 15:09
 */
public class GoodCopyOf {

    public static void main(String[] args) {
        String[] b = {"Tom", "Dick", "Harry"};
        b = (String[]) googCopyOf(b, 10);
        System.out.println(Arrays.toString(b));
    }

    /**
     * 扩容数组
     *
     * @param o
     * @param newLength
     */
    public static Object googCopyOf(Object o, int newLength) {
        Class<?> clazz = o.getClass();
        if (!clazz.isArray()) {
            return null;
        }

        Class<?> componentType = clazz.getComponentType();
        int length = Array.getLength(o);
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(o, 0, newArray, 0, Math.min(length, newLength));
        return newArray;
    }
}
